<template>
	<div class="topbar">
		<van-sticky>
			<van-nav-bar @click-right="$router.push({name: 'search'})" @click-left="clickLeft">
				<template #left>
				  <div class="home-nav">
				    <div class="title">{{Greetings}}</div>
				    <div class="title_sub" v-if="userInfo">{{userInfo.nickName}}</div>
				    <div class="title_sub title_sub--login" v-else>点击登陆账号</div>
				  </div>
				</template>
				<template #right>
				  <div class="home-search">
						<van-icon name="search" color="#3498db" />
						<span>请输入搜索关键词</span>
				  </div>
				</template>
			</van-nav-bar>
		</van-sticky>
	</div>
</template>

<script>
	import { getUserInfo } from '@/api/user.js'
	import { hello } from '@/utils/tools.js'
	import bus from '@/utils/eventBus.js'
	export default {
		data() {
			return {
				Greetings: '',
				userInfo: null
			}
		},
		created() {
			// 问候语
			this.Greetings = hello()
			// 有token的情况下获取用户信息
			if(window.sessionStorage.getItem('token')) {
				// 调用请求
				this._get_user_info()
			}
			// 登录页面以及修改个人资料页面(userset)传递过来的通知
			bus.$on('refresh-userinfo', () => {
				// 调用请求
				console.log('重新请求userinfo')
				this._get_user_info()
			})
		},
		methods: {
			// topbar左侧点击事件
			clickLeft () {
				if(!this.userInfo) return this.$router.push({name: 'Login'}) //未登录，跳转登陆页面
				this.$router.push({name: 'Userset'}) //跳转个人设置页面
			},
			// 获取用户信息
			async _get_user_info () {
				const tokenString = window.sessionStorage.getItem('token')
				const {data: res} = await getUserInfo({tokenString})
				console.log('用户信息',res)
				// 判断状态码
				if (res.code !== 'A001') return this.$toast.fail('请求失败,请重新尝试!')
				const userInfo = JSON.stringify(res.result[0])
				window.sessionStorage.setItem('userInfo',userInfo)
				// 获取用户信息
				this.userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'))
			}
		}
	}
</script>

<style lang="scss" scoped>
	.topbar{
		.home-nav{
			display: flex;
			align-items: center;
			justify-content: center;
			.title{
				font-size: 18px;
				font-weight: bold;
			}
			.title_sub{
				margin-left: 5px;
				font-size: 16px;
				text-decoration: underline;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				width: 80px;
				text-align: left;
			}
			.title_sub--login{
				font-size: 12px;
				text-decoration: none;
			}
		}
		.home-search{
			background-color: #f7f8fa;
			display: flex;
			align-items: center;
			padding-left: 12px;
			height: 34px;
			line-height: 34px;
			border-radius: 17px;
			/deep/ .van-icon{
				margin-right: 4px;
				font-size: 16px;
			}
			span{
				width: 170px;
				text-align: left;
				color: #d1d1d1;
			}
		}
	}
</style>